package com.mc.read.pcApi.service;

import com.alibaba.fastjson.JSON;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.mc.read.common.emun.ServiceCodeEnum;
import com.mc.read.common.exception.ServiceException;
import com.mc.read.dao.mapper.*;
import com.mc.read.dao.models.*;
import com.mc.read.vo.request.BaseRequest;
import com.mc.read.vo.respose.BaseRespose;
import com.mc.read.dao.vo.CollectionVo;
import com.mc.read.dao.vo.PageResposeVo;
import com.mc.read.dao.vo.PageVo;
import com.mc.read.dao.vo.ReadIdListVo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Isolation;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.ObjectUtils;

import java.util.Date;
import java.util.List;

@Service
@Slf4j
@Transactional(propagation = Propagation.REQUIRED, isolation = Isolation.DEFAULT, timeout = 36000, rollbackFor = Exception.class)
public class BookService {
    @Autowired
    BookinformationMapper bookinformationMapper;
    @Autowired
    LabelMapper labelMapper;
    @Autowired
    BooklabelMapper booklabelMapper;
    @Autowired
    UserreadhistoryMapper userreadhistoryMapper;
    @Autowired
    UserreadcollectionMapper userreadcollectionMapper;
    @Autowired
    BooktypeMapper booktypeMapper;
    @Autowired
    BookauditMapper bookauditMapper;
    @Autowired
    FunctionService functionService;

    /**
     * @Author:LiuHao
     * @Date:15:24 2019/5/31
     * 选择书籍类型 selectBookType
     **/
    public BaseRespose selectBookType(BaseRequest baseRequest) {
        log.info("选择书籍类型,参数为{}", JSON.toJSONString(baseRequest));
        BaseRespose baseRespose = new BaseRespose();
        Booktype booktype = null;
        try {
            booktype = JSON.parseObject(JSON.toJSONString(baseRequest.getRequestString()), Booktype.class);
        } catch (Exception e) {
            throw new ServiceException(ServiceCodeEnum.INFO_IS_FAIL, JSON.toJSONString(baseRequest));
        }
        if (ObjectUtils.isEmpty(booktype.getParentid())) {
            throw new ServiceException(203020, "请选择父类型", JSON.toJSONString(baseRequest));
        }
        BooktypeExample example = new BooktypeExample();
        example.createCriteria().andParentidEqualTo(booktype.getParentid());
        example.setOrderByClause("sort");
        baseRespose.setReturnString(booktypeMapper.selectByExample(example));
        return baseRespose;
    }

    /**
     * @Author:LiuHao
     * @Date:15:24 2019/5/31
     * 前台用户添加书籍 userAddBook
     **/
    public BaseRespose userAddBook(BaseRequest baseRequest) {
        log.info("前台用户添加书籍,参数为{}", JSON.toJSONString(baseRequest));
        BaseRespose baseRespose = new BaseRespose();
        //TODO 这块需要设置用户等级大于多少 才有权限添加
        BookauditCustom bookaudit = null;
        try {
            bookaudit = JSON.parseObject(JSON.toJSONString(baseRequest.getRequestString()), BookauditCustom.class);
        } catch (Exception e) {
            throw new ServiceException(ServiceCodeEnum.INFO_IS_FAIL, JSON.toJSONString(baseRequest));
        }
        if (ObjectUtils.isEmpty(bookaudit.getBookname()) || ObjectUtils.isEmpty(bookaudit.getAuthor())
                || ObjectUtils.isEmpty(bookaudit.getIntroduction())
                || ObjectUtils.isEmpty(bookaudit.getMainlevelid()) || ObjectUtils.isEmpty(bookaudit.getMainlevelname())
                || ObjectUtils.isEmpty(bookaudit.getSecondlevelid()) || ObjectUtils.isEmpty(bookaudit.getSecondlevelname())
                || ObjectUtils.isEmpty(bookaudit.getCreateuserid())
                ) {
            throw new ServiceException(ServiceCodeEnum.BAD_REQUEST, JSON.toJSONString(baseRequest));
        }
        BookinformationExample example = new BookinformationExample();
        example.createCriteria().andAuthorEqualTo(bookaudit.getAuthor()).andBooknameEqualTo(bookaudit.getBookname()).andDeletemarkEqualTo(0);
        List<Bookinformation> bookinformationList = bookinformationMapper.selectByExample(example);
        if (bookinformationList.size() > 0) {
            throw new ServiceException(203020, "该书籍已存在", JSON.toJSONString(baseRequest));
        }


        BookauditExample bookauditExample = new BookauditExample();
        bookauditExample.createCriteria().andAuthorEqualTo(bookaudit.getAuthor()).andBooknameEqualTo(bookaudit.getBookname()).andDeletemarkEqualTo(0);
        List<Bookaudit> bookaudits = bookauditMapper.selectByExample(bookauditExample);
        if (bookaudits.size() > 0) {
            Integer status = bookaudits.get(0).getStatus();
            if (status == 0) {
                throw new ServiceException(203020, "该书籍正在审核中", JSON.toJSONString(baseRequest));
            }
            if (status == 2) {
                throw new ServiceException(203020, "该书籍审核不通过，理由为:" + bookaudits.get(0).getNopasstxt(), JSON.toJSONString(baseRequest));
            }

        } else {
            if (!ObjectUtils.isEmpty(bookaudit.getLabelNames()) && bookaudit.getLabelNames().size() > 0) {
                bookaudit.setLabelname(JSON.toJSONString(bookaudit.getLabelNames()));
            }
            bookauditMapper.insertSelective(bookaudit);
        }

//        BaseRespose baseRespose = new BaseRespose();
//        //TODO 这块需要设置用户等级大于多少 才有权限添加
//        BookinformationCustom bookinformationCustom = null;
//        try {
//            bookinformationCustom = JSON.parseObject(JSON.toJSONString(baseRequest.getRequestString()), BookinformationCustom.class);
//        } catch (Exception e) {
//            throw new ServiceException(ServiceCodeEnum.INFO_IS_FAIL, JSON.toJSONString(baseRequest));
//        }
//        if (ObjectUtils.isEmpty(bookinformationCustom.getBookname()) || ObjectUtils.isEmpty(bookinformationCustom.getAuthor())
//                || ObjectUtils.isEmpty(bookinformationCustom.getIntroduction())
//                || ObjectUtils.isEmpty(bookinformationCustom.getMainlevelid()) || ObjectUtils.isEmpty(bookinformationCustom.getMainlevelname())
//                || ObjectUtils.isEmpty(bookinformationCustom.getSecondlevelid()) || ObjectUtils.isEmpty(bookinformationCustom.getSecondlevelname())
//                || ObjectUtils.isEmpty(bookinformationCustom.getCreateuserid())
//                ) {
//            throw new ServiceException(ServiceCodeEnum.BAD_REQUEST, JSON.toJSONString(baseRequest));
//        }
//        BookinformationExample example = new BookinformationExample();
//        example.createCriteria().andAuthorEqualTo(bookinformationCustom.getAuthor()).andBooknameEqualTo(bookinformationCustom.getBookname()).andDeletemarkEqualTo(0);
//        List<Bookinformation> bookinformationList = bookinformationMapper.selectByExample(example);
//        if (bookinformationList.size() > 0) {
//            throw new ServiceException(203020, "该书籍已存在", JSON.toJSONString(baseRequest));
//        }
//
//
//        bookinformationCustom.setCreatedate(new Date());
//        bookinformationMapper.insertGetId(bookinformationCustom);
//        if (!ObjectUtils.isEmpty(bookinformationCustom.getLabelNames()) && bookinformationCustom.getLabelNames().size() > 0) {
////            bookinformationList = bookinformationMapper.selectByExample(example);
////            Bookinformation bookinformation = bookinformationList.get(0);
//            Integer labelid = null;
//            List<Label> labelList = null;
//            LabelExample labelExample = null;
//            Booklabel booklabel = null;
//            Label label = null;
//            for (String labelName : bookinformationCustom.getLabelNames()
//                    ) {
//                labelExample = new LabelExample();
//                labelExample.createCriteria().andBooktypeidEqualTo(bookinformationCustom.getMainlevelid()).andLabelnameEqualTo(labelName);
//                labelList = labelMapper.selectByExample(labelExample);
//                if (labelList.size() == 0) {
//                    label = new Label();
//                    label.setBooktypeid(bookinformationCustom.getMainlevelid());
//                    label.setLabelname(labelName);
//                    labelMapper.insertGetId(label);
//                    System.out.println(label.getLabelid());
//                    labelid = label.getLabelid();
//                } else {
//                    labelid = labelList.get(0).getLabelid();
//                }
//                booklabel = new Booklabel();
//                booklabel.setLabelid(labelid);
//                booklabel.setBookid(bookinformationCustom.getBookinformationid());
//                booklabel.setLikesum(0);
//                booklabel.setHatesum(0);
//                booklabelMapper.insertSelective(booklabel);
//            }
//        }
        functionService.updateFunctionClick("添加书籍");
        baseRespose.setReturnString(" ");
        return baseRespose;
    }

    /**
     * @Author:LiuHao
     * @Date:15:24 2019/5/31
     * 查询我的历史记录 selectReadhistoryList
     **/
    public BaseRespose selectReadhistoryList(BaseRequest baseRequest) {
        log.info("查询我的历史记录,参数为{}", JSON.toJSONString(baseRequest));
        BaseRespose baseRespose = new BaseRespose();
        PageVo pageVo = null;
        try {
            pageVo = JSON.parseObject(JSON.toJSONString(baseRequest.getRequestString()), PageVo.class);
        } catch (Exception e) {
            throw new ServiceException(ServiceCodeEnum.INFO_IS_FAIL, JSON.toJSONString(baseRequest));
        }
        PageHelper.startPage(pageVo.getPagenum(), pageVo.getPagesize());
        PageHelper.orderBy("createDate desc");
        pageVo.setUserid(baseRequest.getUserId());
        List<Userreadhistory> userreadhistoryList = userreadhistoryMapper.selectReadhistoryList(pageVo);
        PageInfo<Userreadhistory> pageInfo = new PageInfo<>(userreadhistoryList);
        PageResposeVo pageResposeVo = new PageResposeVo(pageInfo.getTotal(), pageInfo.getList());
        baseRespose.setReturnString(pageResposeVo);
        return baseRespose;
    }

    /**
     * @Author:LiuHao
     * @Date:15:24 2019/5/31
     * 添加历史记录 addReadhistory
     **/
    public BaseRespose addReadhistory(BaseRequest baseRequest) {
        log.info("添加历史记录,参数为{}", JSON.toJSONString(baseRequest));
        BaseRespose baseRespose = new BaseRespose();
        Userreadhistory userreadhistory = null;
        try {
            userreadhistory = JSON.parseObject(JSON.toJSONString(baseRequest.getRequestString()), Userreadhistory.class);
        } catch (Exception e) {
            throw new ServiceException(ServiceCodeEnum.INFO_IS_FAIL, JSON.toJSONString(baseRequest));
        }
        if (ObjectUtils.isEmpty(userreadhistory.getBookurl())) {
            throw new ServiceException(203020, "链接地址不能为空", JSON.toJSONString(baseRequest));
        }
        if (ObjectUtils.isEmpty(userreadhistory.getBooktitle())) {
            throw new ServiceException(203020, "标题不能为空", JSON.toJSONString(baseRequest));
        }
        if(!ObjectUtils.isEmpty(userreadhistory.getBookid())){
            Bookinformation bookinformation=bookinformationMapper.selectByPrimaryKey(userreadhistory.getBookid());
            if(!ObjectUtils.isEmpty(bookinformation)){
                userreadhistory.setBookname(bookinformation.getBookname());
                userreadhistory.setBooktypename(bookinformation.getMainlevelname());

                //更新用户阅读的书籍
                functionService.updateUserBook(baseRequest.getUserId(),bookinformation);
            }
        }

        userreadhistory.setCreatedate(new Date());
        userreadhistory.setUserid(baseRequest.getUserId());
        userreadhistoryMapper.insertSelective(userreadhistory);
        return baseRespose;
    }

    /**
     * @Author:LiuHao
     * @Date:15:24 2019/5/31
     * 删除历史纪录 delReadhistory
     **/
    public BaseRespose delReadhistory(BaseRequest baseRequest) {
        log.info("删除历史纪录,参数为{}", JSON.toJSONString(baseRequest));
        BaseRespose baseRespose = new BaseRespose();
        ReadIdListVo readHistoryVo = null;
        try {
            readHistoryVo = JSON.parseObject(JSON.toJSONString(baseRequest.getRequestString()), ReadIdListVo.class);
        } catch (Exception e) {
            throw new ServiceException(ServiceCodeEnum.INFO_IS_FAIL, JSON.toJSONString(baseRequest));
        }
        if (readHistoryVo.getType() == 2) {
            UserreadhistoryExample example = new UserreadhistoryExample();
            example.createCriteria().andUseridEqualTo(baseRequest.getUserId());
            userreadhistoryMapper.deleteByExample(example);
        } else {
            if (ObjectUtils.isEmpty(readHistoryVo.getIdlist()) || readHistoryVo.getIdlist().size() == 0) {
                throw new ServiceException(203020, "请选择所要删除的历史纪录", JSON.toJSONString(baseRequest));
            }
            UserreadhistoryExample example = new UserreadhistoryExample();
            example.createCriteria().andUserreadhistoryidIn(readHistoryVo.getIdlist()).andUseridEqualTo(baseRequest.getUserId());
            userreadhistoryMapper.deleteByExample(example);
        }
        functionService.updateFunctionClick("删除历史纪录");
        return baseRespose;
    }

    /**
     * @Author:LiuHao
     * @Date:15:24 2019/5/31
     * 查询我的收藏 selectCollectionList
     **/
    public BaseRespose selectCollectionList(BaseRequest baseRequest) {
        log.info("查询我的收藏,参数为{}", JSON.toJSONString(baseRequest));
        BaseRespose baseRespose = new BaseRespose();
        CollectionVo collectionVo = null;
        try {
            collectionVo = JSON.parseObject(JSON.toJSONString(baseRequest.getRequestString()), CollectionVo.class);
        } catch (Exception e) {
            throw new ServiceException(ServiceCodeEnum.INFO_IS_FAIL, JSON.toJSONString(baseRequest));
        }
        if (ObjectUtils.isEmpty(collectionVo.getType())) {
            throw new ServiceException(203020, "请选择查询的类型", JSON.toJSONString(baseRequest));
        }
        PageHelper.startPage(collectionVo.getPagenum(), collectionVo.getPagesize());
        PageHelper.orderBy("updateDate desc");
        UserreadcollectionExample example = new UserreadcollectionExample();
        if (!ObjectUtils.isEmpty(collectionVo.getSelectinfo())) {
            example.createCriteria().andTypeEqualTo(collectionVo.getType()).andBooktitleLike(collectionVo.getSelectinfo()).andUseridEqualTo(baseRequest.getUserId());
        } else {
            example.createCriteria().andTypeEqualTo(collectionVo.getType()).andUseridEqualTo(baseRequest.getUserId());
        }
        List<Userreadcollection> userreadcollectionList = userreadcollectionMapper.selectByExample(example);
        PageInfo<Userreadcollection> pageInfo = new PageInfo<>(userreadcollectionList);
        PageResposeVo pageResposeVo = new PageResposeVo(pageInfo.getTotal(), pageInfo.getList());
        baseRespose.setReturnString(pageResposeVo);
        return baseRespose;
    }

    /**
     * @Author:LiuHao
     * @Date:15:24 2019/5/31
     * 添加收藏 addCollection
     **/
    public BaseRespose addCollection(BaseRequest baseRequest) {
        log.info("添加收藏,参数为{}", JSON.toJSONString(baseRequest));
        BaseRespose baseRespose = new BaseRespose();
        Userreadcollection userreadcollection = null;
        try {
            userreadcollection = JSON.parseObject(JSON.toJSONString(baseRequest.getRequestString()), Userreadcollection.class);
        } catch (Exception e) {
            throw new ServiceException(ServiceCodeEnum.INFO_IS_FAIL, JSON.toJSONString(baseRequest));
        }
        if (ObjectUtils.isEmpty(userreadcollection.getBookurl())
                || ObjectUtils.isEmpty(userreadcollection.getType())) {
            throw new ServiceException(203020, "参数不完整", JSON.toJSONString(baseRequest));
        }
        UserreadcollectionExample example = new UserreadcollectionExample();
        example.createCriteria().andTypeEqualTo(userreadcollection.getType()).andBooktitleEqualTo(userreadcollection.getBooktitle()).andBookurlEqualTo(userreadcollection.getBookurl());
        example.setOrderByClause("updatedate desc");
        List<Userreadcollection> list = userreadcollectionMapper.selectByExample(example);
        if (list.size() > 0) {
            //更新
            userreadcollection.setUserreadcollectionid(list.get(0).getUserreadcollectionid());
            userreadcollection.setUpdatedate(new Date());
            userreadcollection.setUserid(baseRequest.getUserId());
            userreadcollectionMapper.updateByPrimaryKeySelective(userreadcollection);
        } else {
            if (!ObjectUtils.isEmpty(userreadcollection.getBookid())&&userreadcollection.getBookid()!=0) {
                example = new UserreadcollectionExample();
                example.createCriteria().andBookidEqualTo(userreadcollection.getBookid());
                list = userreadcollectionMapper.selectByExample(example);
                if (list.size() == 0) {
                    //修改小说的收藏数
                    bookinformationMapper.updateCollectionNum(userreadcollection.getBookid());
                }
            }
            if(!ObjectUtils.isEmpty(userreadcollection.getBookid())&&userreadcollection.getBookid()!=0){
                Bookinformation bookinformation=bookinformationMapper.selectByPrimaryKey(userreadcollection.getBookid());
                if(!ObjectUtils.isEmpty(bookinformation)){
                    userreadcollection.setBookname(bookinformation.getBookname());
                    userreadcollection.setBooktypename(bookinformation.getMainlevelname());
                    userreadcollection.setBooktypeid(bookinformation.getMainlevelid());
                }
            }
            userreadcollection.setCreatedate(new Date());
            userreadcollection.setUpdatedate(new Date());
            userreadcollection.setUserid(baseRequest.getUserId());

            userreadcollectionMapper.insertSelective(userreadcollection);
        }
        baseRespose.setReturnString(" ");
        functionService.updateFunctionClick("添加收藏");

        return baseRespose;
    }

    /**
     * @Author:LiuHao
     * @Date:15:24 2019/5/31
     * 删除收藏 deleteCollection
     **/
    public BaseRespose deleteCollection(BaseRequest baseRequest) {
        log.info("删除收藏,参数为{}", JSON.toJSONString(baseRequest));
        BaseRespose baseRespose = new BaseRespose();
        ReadIdListVo readIdListVo = null;
        try {
            readIdListVo = JSON.parseObject(JSON.toJSONString(baseRequest.getRequestString()), ReadIdListVo.class);
        } catch (Exception e) {
            throw new ServiceException(ServiceCodeEnum.INFO_IS_FAIL, JSON.toJSONString(baseRequest));
        }
        if (ObjectUtils.isEmpty(readIdListVo.getIdlist()) || readIdListVo.getIdlist().size() == 0) {
            throw new ServiceException(203020, "请选择所要删除的历史纪录", JSON.toJSONString(baseRequest));
        }
        if (ObjectUtils.isEmpty(readIdListVo.getCollectionType())) {
            throw new ServiceException(203020, "请选择收藏类型", JSON.toJSONString(baseRequest));
        }
        UserreadcollectionExample example = new UserreadcollectionExample();
        example.createCriteria().andUserreadcollectionidIn(readIdListVo.getIdlist()).andUseridEqualTo(baseRequest.getUserId()).andTypeEqualTo(readIdListVo.getCollectionType());
        userreadcollectionMapper.deleteByExample(example);
        baseRespose.setReturnString(" ");
        functionService.updateFunctionClick("删除收藏");

        return baseRespose;
    }

}
